package sen.myReport;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.SessionFactory;

import sen.queryUtils.Cond;
import sen.queryUtils.Conditional;
import sen.queryUtils.MyUtils;
import sen.queryUtils.Results;

public class MyReportServiceImpl implements MyReportService {

	private List<MyReportData> myReports;
	private Map<String, MyReportData> reportDatas;
	private SessionFactory sessionFactory;
	
	public MyReportData getReportData(String reqReportId, List<Cond> cond) throws Exception {
		Results r = query(reqReportId, cond);
		MyReportData d = reportDatas.get(reqReportId);
		
		//在具体的报表中得到excel的数据
		List<ExcelSheet> es = d.getExcelData((List)r.getDatas());
		//检查excel数据中是否已经设置了label和head，没有则设置为配置文件中的，配置文件也没有则报错。
		for (int i = 0; i < es.size(); i++) {
			ExcelSheet excelSheet = es.get(i);
			if(excelSheet.getLabelName()==null || "".equals(excelSheet.getLabelName())) {
				String label = "report";
				if(d.getLabel()!=null){
					label = d.getLabel().get(i);
				}
				excelSheet.setLabelName(label);
			}
			if(excelSheet.getHead()==null || excelSheet.getHead().length < 1) {
				String[] head = d.getHead().get(i).split(Constant.SEPARATOR);
				excelSheet.setHead(head);
			}
		}
		
		ExcelExportHelper2 e = new ExcelExportHelper2(es);
		d.setDatas(e.getExcelByteArray());
		return d;
	}

	public Results query(String reqReportId, List<Cond> cond) throws Exception {
		MyReportData d = reportDatas.get(reqReportId);
		if(d == null) {
			throw new RuntimeException("没有找到报表【"+reqReportId+"】");
		}
		//设置报表名称----------start
		String tep = "";
		for (Iterator iterator = cond.iterator(); iterator.hasNext();) {
			Conditional c = (Conditional) iterator.next();
			if(c.getName().equals("reportName")) {
				tep = c.getValue();
				iterator.remove();
				break;
			}
		}
		if(MyUtils.isNull(tep)){
			tep = "report";
		}
		d.setMyReportName(tep+".xls");
		//设置报表名称----------end
		return d.query(sessionFactory, cond);
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public String getResponsePage(String reportName) {
		return reportDatas.get(reportName).getResponsePage();
	}

	public void setMyReports(List<MyReportData> myReports) {
		this.myReports = myReports;
		reportDatas = MyReportDataFactory.createInstance().getAllMyReports(myReports);
	}
}